/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime/debug"

	"github.com/deploy-services/v2/filesystem"
	"github.com/deploy-services/v2/kcfg"
	"github.com/spf13/cobra"
)

var cmd_url_prefix string
var config_file string = ".cli.kcfg"

func get_config_file() string {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		panic(err)
	}
	return filepath.Join(homeDir, config_file)
}

var configCmd = &cobra.Command{
	Use: "config",
	Run: func(cmd *cobra.Command, args []string) {
		host, _ := cmd.Flags().GetString("host")
		port, _ := cmd.Flags().GetInt16("port")
		file := get_config_file()
		url := fmt.Sprintf("http://%v:%v", host, port)
		cfg := kcfg.NewCfg()
		cfg.Add("server.url", url)
		content := cfg.Dump()
		ioutil.WriteFile(file, []byte(content), 0666)
	},
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use: "deploy-cli",
	// Uncomment the following line if your bare application
	// has an action associated with it:
	PersistentPreRun: func(cmd *cobra.Command, args []string) {

		host, _ := cmd.Flags().GetString("host")
		port, _ := cmd.Flags().GetInt16("port")
		cmd_url_prefix = fmt.Sprintf("http://%v:%v", host, port)
		//  如果配置文件存在，使用配置文件
		file := get_config_file()
		if !filesystem.IsExist(file) {
			return
		}
		defer func() {
			if r := recover(); r != nil {
				fmt.Println(fmt.Sprintln(r))
				fmt.Println(string(debug.Stack()))
			}
		}()
		cfg := kcfg.NewCfg()
		cfg.ParseFile(file)
		n := cfg.Child("server.url")
		if n != kcfg.NullNode {
			cmd_url_prefix = n.GetString()
		}
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.AddCommand(configCmd)
	rootCmd.PersistentFlags().StringP("host", "H", "127.0.0.1", "Deploy service host ip")
	rootCmd.PersistentFlags().Int16P("port", "p", 10802, "Deploy service port")
}
